import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import {Alert, AutoComplete, Button, Card, Form, FormListFieldData, Input, Select, Space, Typography} from 'antd';
import { useEffect, useState } from 'react';

interface Props {
  formRef: any;
}

const { Text } = Typography;

// 模型配置表单组件
export default (props: Props) => {
  const { formRef } = props;
  const [hasGroup, setHasGroup] = useState(false);

  // 初始化检查是否已有分组配置
  useEffect(() => {
    const initialGroup = formRef.current?.getFieldValue(['modelConfig', 'modelGroupConfig']);
    setHasGroup(!!initialGroup);
  }, []);

  // 单字段表单项样式
  const formItemStyle = {
    marginBottom: 16,
    minWidth: 200,
  };

  // 添加分组配置
  const handleAddGroup = () => {
    const currentModelConfig = formRef.current?.getFieldsValue().modelConfig || {};
    if (!currentModelConfig.modelGroupConfig) {
      formRef.current?.setFieldsValue({
        modelConfig: {
          ...currentModelConfig,
          modelGroupConfig: {
            condition: '',
            description: '',
            groupKey: '',
            groupName: '',
            type: '',
          },
        },
      });
      setHasGroup(true);
    }
  };

  // 删除分组配置
  const handleRemoveGroup = () => {
    const currentModelConfig = formRef.current?.getFieldsValue().modelConfig || {};
    const newModelConfig = { ...currentModelConfig };
    delete newModelConfig.modelGroupConfig;
    formRef.current?.setFieldsValue({
      modelConfig: newModelConfig,
    });
    setHasGroup(false);
  };

  /**
   * 单个字段表单视图
   */
  const singleFieldFormView = (
    field: FormListFieldData,
    remove?: (index: number | number[]) => void,
  ) => {
    return (
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Form.Item
          label="字段名称"
          name={[field.name, 'fieldName']}
          style={formItemStyle}
          labelCol={{ span: 10 }}
          wrapperCol={{ span: 16 }}
          rules={[
            {
              required: true,
              message: '请输入字段名称',
            },
          ]}
        >
          <Input placeholder="请输入字段名称" />
        </Form.Item>
        <Form.Item
          label="描述"
          name={[field.name, 'description']}
          style={formItemStyle}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Input placeholder="请输入描述" />
        </Form.Item>
        <Form.Item
          label="类型"
          name={[field.name, 'type']}
          style={formItemStyle}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 18 }}
          rules={[
            {
              required: true,
              message: '请选择类型',
            },
          ]}
        >
          <Select placeholder="请选择类型">
            <Select.Option value="String">字符串</Select.Option>
            <Select.Option value="boolean">布尔值</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="默认值"
          name={[field.name, 'defaultValue']}
          style={formItemStyle}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 18 }}
          rules={[
            {
              required: true,
              message: '请输入或选择默认值',
            },
          ]}
          // 将表单中的布尔值转换为字符串供AutoComplete显示
          getValueProps={(value) => ({
            value: typeof value === 'boolean' ? value.toString() : value,
          })}
          // 将用户输入的字符串转换为布尔值保存
          getValueFromEvent={(value) => {
            if (value === 'true') return true;
            if (value === 'false') return false;
            return value; // 保留其他输入情况
          }}
        >
          <AutoComplete
            placeholder="请输入或选择默认值"
            options={[
              { label: '是（true）', value: 'true' },
              { label: '否（false）', value: 'false' },
            ]}
            filterOption={(inputValue, option) =>
              option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
            }
          />
        </Form.Item>
        <Form.Item
          label="被替换内容"
          name={[field.name, 'replaceText']}
          style={formItemStyle}
          labelCol={{ span: 10 }}
          wrapperCol={{ span: 20 }}
        >
          <Input placeholder="不填则不替换代码内容" />
        </Form.Item>
        <Form.Item
          label="缩写"
          name={[field.name, 'abbr']}
          style={formItemStyle}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Input placeholder="请输入缩写" />
        </Form.Item>
        {remove && (
          <Button
            type="text"
            danger
            onClick={() => remove(field.name)}
            style={{ alignSelf: 'flex-end', marginBottom: 16 }}
            icon={<CloseOutlined />}
          />
        )}
      </div>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <Alert
        message="如果不替换代码内容，则不填写被替换内容,请在提交前删除为空的配置"
        type="warning"
        closable
      />
      {/* 分组配置卡片 */}
      {hasGroup && (
        <Card
          size="small"
          title={
            <Text strong style={{ color: '#1890ff' }}>
              模型分组配置
            </Text>
          }
          headStyle={{
            backgroundColor: '#f0f9ff',
            borderBottom: '2px solid #1890ff',
          }}
          style={{ borderRadius: 8 }}
          extra={
            <CloseOutlined
              onClick={handleRemoveGroup}
              style={{ color: '#999', fontSize: 14, cursor: 'pointer' }}
            />
          }
        >
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            <Form.Item
              label="分组 Key"
              name={['modelConfig', 'modelGroupConfig', 'groupKey']}
              style={formItemStyle}
              labelCol={{ span: 10 }}
              wrapperCol={{ span: 16 }}
              rules={[
                {
                  required: true,
                  message: '请输入分组key',
                },
              ]}
            >
              <Input placeholder="分组唯一标识" required />
            </Form.Item>
            <Form.Item
              label="组名"
              name={['modelConfig', 'modelGroupConfig', 'groupName']}
              style={formItemStyle}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
            >
              <Input placeholder="显示用组名" />
            </Form.Item>
            <Form.Item
              label="类型"
              name={['modelConfig', 'modelGroupConfig', 'type']}
              style={formItemStyle}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
            >
              <Input placeholder="分组类型" />
            </Form.Item>
            <Form.Item
              label="条件"
              name={['modelConfig', 'modelGroupConfig', 'condition']}
              style={formItemStyle}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
            >
              <Input placeholder="生效条件" />
            </Form.Item>
            <Form.Item
              label="描述"
              name={['modelConfig', 'modelGroupConfig', 'description']}
              style={formItemStyle}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
            >
              <Input placeholder="分组描述" />
            </Form.Item>
          </div>
        </Card>
      )}

      {/* 独立模型配置列表 */}
      <Form.List name={['modelConfig', 'models']}>
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => (
              <Card
                key={field.key}
                size="small"
                title={<Text strong>模型配置</Text>}
                style={{ borderRadius: 8 }}
                extra={
                  <CloseOutlined
                    onClick={() => remove(field.name)}
                    style={{ color: '#999', fontSize: 14, cursor: 'pointer' }}
                  />
                }
              >
                {singleFieldFormView(field)}
              </Card>
            ))}

            <Button
              type="dashed"
              onClick={() => add()}
              icon={<PlusOutlined />}
            >
              添加模型配置
            </Button>
          </>
        )}
      </Form.List>

      {/* 操作按钮区域 */}
        <Button type="primary" onClick={handleAddGroup} icon={<PlusOutlined />} disabled={hasGroup}>
          添加分组模型配置
        </Button>
      <div style={{ marginBottom: 16 }} />
    </div>
  );
};
